package com.cuit.food.food.Yservice;

import com.cuit.food.Food;
import com.cuit.food.Resturant;
import com.cuit.food.ResturantToFood;
import com.cuit.food.food.Ycommen.MainpageResInfo;
import com.cuit.food.food.Ycommen.RestType;
import com.cuit.food.food.Ycommen.SearchOp;
import common.result.CodeEnum;
import common.result.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class pageinfoservice {

    @Autowired
    resturantservice RestService;

    @Autowired
    foodservice Foodservice;

    @Autowired
    ResToFoodService ResToFood;

    @Autowired
    UserCommentservice UserComment;

    /**
     * 返回前端筛选所有包含typename(food)且价格小于price的商店信息
     * @param typename
     * @param price
     * @param longitude
     * @param latitude
     * @param flag
     * @return
     */
    public ResponseResult FindResByPriceAndType(String typename, long price,
                                double longitude, double latitude, int flag) {
        List<Food> FoodList = null;
        //总榜要查所有种类食物
        if(typename.equals(RestType.DEFULE.getTypename())) {
            System.out.println("!!!-------");
            FoodList = Foodservice.findAll();
        }
        else FoodList = Foodservice.findByCatalogAndPriceLessThanEqual(typename, price);

        //得到目标菜品id,饭店只要包含其中一个就行
        Set<String> set = new HashSet<String>();
        for(Food food : FoodList) {
            set.add(food.getId());
            System.out.println("满足的id:"+food.getId());
        }

        ArrayList<MainpageResInfo> Results = new ArrayList<>();

        List<Resturant> RestList = RestService.findall();
        for(Resturant resturant : RestList) {
            List<ResturantToFood> RestaurantsToFoods = ResToFood.findAllByResId(
                    resturant.getId());
            System.out.println("从" + resturant.getName()+"中查找");
            for(ResturantToFood resturantToFood : RestaurantsToFoods) {
                System.out.println(resturantToFood.getFoodId());
                System.out.println(set.contains(resturantToFood.getFoodId()));
                //如果饭店对应的菜品中含有目标菜品
                if(set.contains(resturantToFood.getFoodId())) {
                    System.out.println("get!!");
                    //获得饭店的名字
                    String name = resturant.getName();
                    //获得饭店的图片url
                    String url = resturant.getPictureUrl();
                    //获得用户评分平均值
                    double score = UserComment.GetRestScore(resturant.getId());
                    //获得用户评论数量
                    int CommentNum = UserComment.GetRestCommentCount(resturant.getId());
                    //获得用户最简单的0-2条评论
                    ArrayList<String> UserComment = this.UserComment.FindrescommentByid(
                            resturant.getId());
                    //获得距离
                    double dis = getDistance(latitude, longitude,
                            resturant.getLatitude(), resturant.getLongitude());

                    MainpageResInfo item = new MainpageResInfo();
                    item.setResName(name);
                    item.setPictureUrl(url);
                    item.setStarNum(score);
                    item.setCommentNum(CommentNum);
                    item.setUserComment(UserComment);
                    item.setRestid(resturant.getId());
                    item.setDis(dis);
                    Results.add(item);
                    break;
                }
            }
        }

        //如果前端需要按照距离排序
        if(SearchOp.ORDERED.getFlag() == flag) {
            Comparator<MainpageResInfo>cmp = Comparator.comparing(MainpageResInfo::getDis);
            Results.sort(cmp);
        }
        else if(SearchOp.START.getFlag() == flag) {
            //按照评分数降序排序
            Comparator<MainpageResInfo>cmp = Comparator.comparing(MainpageResInfo::getStarNum);
            Results.sort(cmp.reversed());
        }
        return new ResponseResult(CodeEnum.SUCCESS.getCode(), Results);
    }


    public static double getDistance(Double lat1,Double lng1,Double lat2,Double lng2) {
        // 经纬度（角度）转弧度。弧度用作参数，以调用Math.cos和Math.sin
        double radiansAX = Math.toRadians(lng1); // A经弧度
        double radiansAY = Math.toRadians(lat1); // A纬弧度
        double radiansBX = Math.toRadians(lng2); // B经弧度
        double radiansBY = Math.toRadians(lat2); // B纬弧度

        // 公式中“cosβ1cosβ2cos（α1-α2）+sinβ1sinβ2”的部分，得到∠AOB的cos值
        double cos = Math.cos(radiansAY) * Math.cos(radiansBY) * Math.cos(radiansAX - radiansBX)
                + Math.sin(radiansAY) * Math.sin(radiansBY);
//        System.out.println("cos = " + cos); // 值域[-1,1]
        double acos = Math.acos(cos); // 反余弦值
//        System.out.println("acos = " + acos); // 值域[0,π]
//        System.out.println("∠AOB = " + Math.toDegrees(acos)); // 球心角 值域[0,180]
        return 6371393 * acos/1000; // 最终结果
    }
}
